package com.lhh.springcommon.aspect;

import com.lhh.springcommon.utils.Response;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.Objects;

/**
 * 请求id切面
 * @author 李厚航
 */
@Aspect
@Component
@Slf4j
public class RequestIdAspect {

    @Around("@annotation(com.lhh.springcommon.annotation.WithRequestId)")
    public Object around(ProceedingJoinPoint joinPoint) throws Throwable {
        // 获取当前请求
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = Objects.requireNonNull(attributes).getRequest();

        // 获取请求头中的 requestId
        String requestId = request.getHeader("requestId");

        // 执行目标方法
        Object result = joinPoint.proceed();

        // 如果返回值是 ResponseResult 类型，设置 requestId
        if (result instanceof Response) {
            Response<?> responseResult = (Response<?>) result;
            responseResult.setRequestId(requestId);
        }

        return result;
    }
}
